/**
 * Copyright (c) 2019 Coder League
 * All rights reserved.
 *
 * File：SessionUtils.java
 * History:
 *         2019年5月11日: Initially created, CJH.
 */
package club.coderleague.ilsp.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import club.coderleague.ilsp.common.domain.beans.UserSession;

/**
 * 普通类中获取session
 * 
 * @author CJH
 */
public class SessionUtil {
	
	/**
	 * 获取当前线程绑定的{@link HttpServletRequest}
	 * 
	 * @author CJH 2019年5月11日
	 * @return 当前线程绑定的{@link HttpServletRequest}，如果没有则为{@code null}
	 */
	public static HttpServletRequest getHttpServletRequest() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return requestAttributes != null ? ((ServletRequestAttributes) requestAttributes).getRequest() : null;
	}
	
	/**
	 * 获取当前线程绑定的{@link HttpSession}
	 * 
	 * @author CJH 2019年5月11日
	 * @return 当前线程绑定的{@link HttpSession}，如果没有则为{@code null}
	 */
	public static HttpSession getHttpSession() {
		HttpServletRequest request = getHttpServletRequest();
		return request != null ? request.getSession() : null;
	}
	
	/**
	 * 获取用户信息
	 * 
	 * @author CJH 2019年5月11日
	 * @return 用户信息
	 */
	public static UserSession getUserSession() {
		try {
			return (UserSession) getHttpSession().getAttribute(UserSession.SESSION_KEY);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 获取目标主机IP地址
	 * 
	 * @author CJH 2019年5月11日
	 * @return IP地址
	 */
	public static String getRemoteHost() {
		HttpServletRequest request = getHttpServletRequest();
		if (request == null) {
			return null;
		}
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
}
